package com.baosight.risk.service.riim.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baosight.risk.api.fltd.FlaaNodeAuthoService;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.riim.RiimRiskImportForSubService;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.fltd.FlaaNodeAuthoMapper;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.mapper.riim.RiimRiskAssignmentMapper;
import com.baosight.risk.mapper.riim.RiimRiskEvaluationMapper;
import com.baosight.risk.mapper.riim.RiimRiskGoalDetailMapper;
import com.baosight.risk.mapper.riim.RiimRiskGoalMapper;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.fltd.vo.NodeTransitionVO;
import com.baosight.risk.service.riim.entity.RiimRiskAssignment;
import com.baosight.risk.service.riim.entity.RiimRiskEvaluation;
import com.baosight.risk.service.riim.entity.RiimRiskGoal;
import com.baosight.risk.service.riim.entity.RiimRiskGoalDetail;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.xtzy.entity.XtzyUser;

import lombok.extern.slf4j.Slf4j;
@Service("riimRiskImportForSubServiceImpl")
@Slf4j
public class RiimRiskImportForSubServiceImpl extends BaseServiceImpl<RiimRiskImport> implements RiimRiskImportForSubService {
    @Autowired
    private RiimRiskImportMapper riskImportMapper;
    @Autowired
    private RiimRiskEvaluationMapper riskEvaluationMapper;
    @Autowired
    private RiimRiskGoalMapper riskGoalMapper;
    @Autowired
    private RiimRiskGoalDetailMapper riskGoalDetailMapper;
    @Autowired
    private RiimRiskAssignmentMapper riskAssignmentMapper;
    @Autowired
    private FltdProcessService fltdProcessService;
    @Autowired
    private XtzyUserMapper xtzyUserMapper;
    @Autowired
    private FltdTaskMapper fltdTaskMapper;
    @Autowired
    private FlaaNodeAuthoMapper flaaNodeAuthoMapper;
    @Autowired
    private FlaaNodeAuthoService flaaNodeAuthoService;
    
	@Override
	public BaseMapper getMapper() {
		// TODO Auto-generated method stub
		return riskImportMapper;
	}

	/**
	 * 子公司流程调整-风险管理部门主管领导审核完成
	 */
	@Override
	@Transactional
	public void pushRisk(String id) throws Exception{
		RiimRiskImport riskImport = riskImportMapper.selectByPrimaryKey(id);
		if("B09".equals(riskImport.getPlanStatus())){
			//检查是否存在和上级管理单位相同的重点风险；
			if(StringUtils.isNotBlank(riskImport.getParentId())){
				//如果存在相同数据，则复制实施方案，复制相关附件；
				RiimRiskImport parentPlan = riskImportMapper.selectByPrimaryKey(riskImport.getParentId());
				if(parentPlan != null){
					String planStatus = parentPlan.getPlanStatus();
					if("B01".equals(planStatus)){
						this.copy(riskImport, parentPlan);
						this.submit(parentPlan);
					}else if("B05".equals(planStatus)||"B07".equals(planStatus)||"B08".equals(planStatus)||"B09".equals(planStatus)){

					}else{
						throw new Exception("宝钢股份重点风险实施方案的工作流节点不符合条件，请先提交宝钢股份相同重点风险风险的工作流");
					}
				}
			}
		}
	}
	
	private void copy(RiimRiskImport subPlan,RiimRiskImport parentPlan){
		//复制实施方案
		parentPlan.setPlanBeginDate(subPlan.getPlanBeginDate());
		parentPlan.setPlanEndDate(subPlan.getPlanEndDate());
		parentPlan.setDutyLeadCode(subPlan.getDutyLeadCode());
		parentPlan.setDutyLeadName(subPlan.getDutyLeadName());
		parentPlan.setExeLeadCode(subPlan.getExeLeadCode());
		parentPlan.setExeLeadName(subPlan.getExeLeadName());
		parentPlan.setDutyCompCode(subPlan.getDutyCompCode());
		parentPlan.setDutyCompName(subPlan.getDutyCompName());
		parentPlan.setAuxiliaryCompCode(subPlan.getAuxiliaryCompCode());
		parentPlan.setAuxiliaryCompName(subPlan.getAuxiliaryCompName());
		parentPlan.setEditorCode(subPlan.getEditorCode());
		parentPlan.setEditorName(subPlan.getEditorName());
		parentPlan.setRiskDesc(subPlan.getRiskDesc());
		parentPlan.setAdvanceMechanism(subPlan.getAdvanceMechanism());
		parentPlan.setTrainNeed(subPlan.getTrainNeed());
		riskImportMapper.updateByPrimaryKeySelective(parentPlan);
		
		subPlan.setExt5(parentPlan.getId());
		riskImportMapper.updateByPrimaryKeySelective(subPlan);
		
		this.copyEvaluation(subPlan, parentPlan);
		this.copyGoal(subPlan, parentPlan);
		this.copyAssignment(subPlan, parentPlan);
		//复制相关附件
/*		try {
			String sourceModel = "T_RIRE_RISK_WARNING_STATUS_"+subPlan.getAcctYear();
			attachService.copyAttach(subPlan.getId(), sourceModel, parentPlan.getId(),"");
		} catch (Exception e) {
			e.printStackTrace();
		}*/
	}
	
	//复制风险评估
	private void copyEvaluation(RiimRiskImport subPlan,RiimRiskImport parentPlan){
		//先删除宝钢股份风险评估
		RiimRiskEvaluation deleteParam = new RiimRiskEvaluation();
		deleteParam.setImportGuid(parentPlan.getId());
		riskEvaluationMapper.delete(deleteParam);
		//复制
		RiimRiskEvaluation qParam = new RiimRiskEvaluation();
		qParam.setImportGuid(subPlan.getId());
		List<RiimRiskEvaluation> subList = riskEvaluationMapper.select(qParam);
		for(RiimRiskEvaluation subEvaluation : subList){
			subEvaluation = (RiimRiskEvaluation) BeanUtils.initBean(subEvaluation);
			subEvaluation.setImportGuid(parentPlan.getId());
			riskEvaluationMapper.insert(subEvaluation);
		}
	}

	//复制项目目标
	private void copyGoal(RiimRiskImport subPlan,RiimRiskImport parentPlan){
		//先删除宝钢股份项目目标
		RiimRiskGoal dParam = new RiimRiskGoal();
		dParam.setImportGuid(parentPlan.getId());
		riskGoalMapper.delete(dParam);
		RiimRiskGoalDetail ddParam = new RiimRiskGoalDetail();
		ddParam.setImportGuid(parentPlan.getId());
		riskGoalDetailMapper.delete(ddParam);
		//复制项目目标
		RiimRiskGoal qParam = new RiimRiskGoal();
		qParam.setImportGuid(subPlan.getId());
		List<RiimRiskGoal> subList = riskGoalMapper.select(qParam);
		for(RiimRiskGoal subGoal : subList){
			//取detail表数据，保存到内存
			RiimRiskGoalDetail qdParam = new RiimRiskGoalDetail();
			qdParam.setImportGuid(subPlan.getId());
			qdParam.setGoalId(subGoal.getId());
			List<RiimRiskGoalDetail> detailList = riskGoalDetailMapper.select(qdParam);
			
			//复制主表
			subGoal = (RiimRiskGoal) BeanUtils.initBean(subGoal);
			subGoal.setImportGuid(parentPlan.getId());
			riskGoalMapper.insert(subGoal);
			
			//复制detail表
			for(RiimRiskGoalDetail subDetail : detailList){
				subDetail = (RiimRiskGoalDetail) BeanUtils.initBean(subDetail);
				subDetail.setImportGuid(parentPlan.getId());
				subDetail.setGoalId(subGoal.getId());
				riskGoalDetailMapper.insert(subDetail);
			}
		}
	}
	
	//复制主要职责及分工
	private void copyAssignment(RiimRiskImport subPlan,RiimRiskImport parentPlan){
		//先删除主要职责及分工
		RiimRiskAssignment deleteParam = new RiimRiskAssignment();
		deleteParam.setImportGuid(parentPlan.getId());
		riskAssignmentMapper.delete(deleteParam);
		//复制
		RiimRiskAssignment qParam = new RiimRiskAssignment();
		qParam.setImportGuid(subPlan.getId());
		List<RiimRiskAssignment> subList = riskAssignmentMapper.select(qParam);
		for(RiimRiskAssignment subAssignment : subList){
			subAssignment = (RiimRiskAssignment) BeanUtils.initBean(subAssignment);
			subAssignment.setImportGuid(parentPlan.getId());
			riskAssignmentMapper.insert(subAssignment);
		}
	}
	
	private void submit(RiimRiskImport parentPlan){
        if(StringUtils.isNotEmpty(parentPlan.getDutyUserCode())){
            XtzyUser xtzyUser = xtzyUserMapper.selectByName(parentPlan.getDutyUserCode());
            FltdTaskVO paramTask=new FltdTaskVO();
            paramTask.setFlowNo("fengxianshishifangan");
            paramTask.setBizGuid(parentPlan.getId());
            paramTask.setNodeCode(parentPlan.getPlanStatus());
            paramTask.setStatus("open");
            List<FltdTask> taskList = fltdTaskMapper.selectTaskList(paramTask);
            if(taskList.size()>0){
                FltdTaskVO taskVoParam=new FltdTaskVO();
                BeanUtils.copyBeanProp(taskVoParam, taskList.get(0));
                try {
                    FltdTask updateTask=new FltdTask();
                    updateTask.setTodoGuid(taskVoParam.getTodoGuid());
                    //走绿色通道
                    updateTask.setGreenFlag("G");
                    fltdTaskMapper.updateByPrimaryKeySelective(updateTask);
                    taskVoParam.setGreenFlag("G");

                    //获取下一节点审批人
                    Map<String, Object> resultMap = flaaNodeAuthoService.getNextUser(taskVoParam, xtzyUser);
                    List<XtzyUser> authUsers = (List<XtzyUser>)resultMap.get("authUsers");
                    if(CollectionUtils.isNotEmpty(authUsers)){
                    	taskVoParam.setCustomUsers(authUsers);
                    	
                    	//查询指定节点的下一个节点及转移路线
                        String processDefId = fltdProcessService.getProcessDefId(taskVoParam.getProcGuid());                 
                        NodeTransitionVO nextTransition = flaaNodeAuthoMapper.nextOneNodeTransition(processDefId, "submit-G-1");
                        taskVoParam.setSubmitButton(nextTransition);
                        
    					fltdProcessService.doSubmit(xtzyUser,taskVoParam);
                    }

				} catch (Exception e) {
					throw new RuntimeException(e.getMessage());
				}
            }
        }
	}
}
